package com.hsb.seckill.controller;

import com.hsb.seckill.entity.User;
import com.hsb.seckill.result.ResBean;
import com.hsb.seckill.result.ResBeanEnum;
import com.hsb.seckill.service.GoodsService;
import com.hsb.seckill.service.UserService;
import com.hsb.seckill.utils.UUIDUtil;
import com.hsb.seckill.vo.GoodsDetailVo;
import com.hsb.seckill.vo.GoodsVo;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 商品
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private UserService userService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    //@Autowired
    //private Redisson redisson;

    /**
     * 页面缓存未优化前：392
     * 页面缓存未优化后：1440
     * 检验用户，跳转商品页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/toList",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response){
        if (null == user){
            //return "login";
            WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale());
            return thymeleafViewResolver.getTemplateEngine().process("login", context);
        }
        // 商品列表页面缓存，redis获取页面，如果不为空，直接获取页面
        String html = (String) redisTemplate.opsForValue().get("goodsList");
        if (!StringUtils.isEmpty(html)){
            return html;
        }

        //redis实现分布式锁
        String uuid = UUIDUtil.uuid();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent("goods", uuid, 30, TimeUnit.SECONDS);
        if (flag){
            try{
                // 查询所有秒杀商品
                List<GoodsVo> goodsList = goodsService.querySeckillGoods();
                model.addAttribute("goodsList",goodsList);
                model.addAttribute("user",user);

                //如果为空，利用thymeleaf手动渲染页面，存储redis中
                WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
                html = thymeleafViewResolver.getTemplateEngine().process("goods_list", context);
                if (!StringUtils.isEmpty(html)){
                    redisTemplate.opsForValue().set("goodsList",html,1, TimeUnit.SECONDS);
                }
            }finally {
                if (uuid.equals(redisTemplate.opsForValue().get("goods"))){
                    redisTemplate.delete("goods");
                }
            }
        }

        return html;
    }

    //@RequestMapping( "/toList")
    //public String toList(Model model, User user){
    //    if (null == user){
    //        return "login";
    //    }
    //    // 查询所有秒杀商品
    //    List<GoodsVo> goodsList = goodsService.querySeckillGoods();
    //    model.addAttribute("goodsList",goodsList);
    //    model.addAttribute("user",user);
    //    return "goods_list";
    //}

    /**
     * 秒杀商品详情页
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/toDetail/{goodsId}",method = RequestMethod.GET)
    @ResponseBody
    public ResBean toDetail(User user, @PathVariable("goodsId") Integer goodsId){
        if (null == user){
            return ResBean.error(ResBeanEnum.USER_NOT_LOGIN);
        }

        //根据商品id查询秒杀商品
        GoodsVo goods = goodsService.querySeckillGoodsById(goodsId);
        //秒杀状态
        int miaoshaStatus = 0;
        //秒杀开始倒计时
        int remainSeconds = 0;
        //秒杀结束倒计时
        int betweenSeconds = 0;
        //秒杀开始时间
        Date startDate = goods.getStartDate();
        //秒杀结束时间
        Date endDate = goods.getEndDate();
        //获取当前时间
        Date nowDate = new Date();

        if (nowDate.after(endDate)){//秒杀已结束
            miaoshaStatus = 2;
            remainSeconds=-1;
        }else if (nowDate.before(startDate)){//秒杀倒计时
            remainSeconds = (int) ((startDate.getTime()- nowDate.getTime())/1000);
        }else {//秒杀中
            miaoshaStatus = 1;
        }
        //秒杀结束倒计时
        betweenSeconds = (int) ((endDate.getTime()-startDate.getTime())/1000);

        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        goodsDetailVo.setUser(user);
        goodsDetailVo.setGoodsVo(goods);
        goodsDetailVo.setRemainSeconds(remainSeconds);
        goodsDetailVo.setMiaoshaStatus(miaoshaStatus);
        //goodsDetailVo.setEndDate(endDate);

        return ResBean.success(goodsDetailVo);
    }
    //@RequestMapping("/toDetail/{goodsId}")
    //public String toDetail(Model model, User user, @PathVariable("goodsId") Integer goodsId){
    //    if (null == user){
    //        return "login";
    //    }
    //
    //    //根据商品id查询秒杀商品
    //    GoodsVo goods = goodsService.querySeckillGoodsById(goodsId);
    //    //秒杀状态
    //    int miaoshaStatus = 0;
    //    //秒杀开始倒计时
    //    int remainSeconds = 0;
    //    //秒杀结束倒计时
    //    int betweenSeconds = 0;
    //    //秒杀开始时间
    //    Date startDate = goods.getStartDate();
    //    //秒杀结束时间
    //    Date endDate = goods.getEndDate();
    //    //获取当前时间
    //    Date nowDate = new Date();
    //
    //    if (nowDate.after(endDate)){//秒杀已结束
    //        miaoshaStatus = 2;
    //        remainSeconds=-1;
    //    }else if (nowDate.before(startDate)){//秒杀倒计时
    //        remainSeconds = (int) ((startDate.getTime()- nowDate.getTime())/1000);
    //    }else {//秒杀中
    //        miaoshaStatus = 1;
    //    }
    //    //秒杀结束倒计时
    //    betweenSeconds = (int) ((endDate.getTime()-startDate.getTime())/1000);
    //
    //    model.addAttribute("betweenSeconds",betweenSeconds);
    //    model.addAttribute("remainSeconds",remainSeconds);
    //    model.addAttribute("miaoshaStatus",miaoshaStatus);
    //    model.addAttribute("goods",goods);
    //    model.addAttribute("user",user);
    //
    //    return "goods_detail";
    //}
}
